package cn.edu.neu.lab603.cloudeval.monitor

import cn.edu.neu.lab603.cloudeval.CloudEval
import cn.edu.neu.lab603.cloudeval.entity.{PhysicalMachine, VirtualMachine}
import cn.edu.neu.lab603.des.SimMonitor

import scala.collection.mutable

/** 停机时间监视器。
  *
  * Created by yfwz100 on 2016/11/6.
  */
class MigrationDownTimeMonitor extends SimMonitor[CloudEval] {

  val stats = new mutable.HashMap[Long, mutable.ListBuffer[Long]]
  private val start = new mutable.HashMap[Long, Long]

  override def isMatch(context: CloudEval): Boolean = context.getCurrentTask match {
    case _: PhysicalMachine.VMMigrateInEvent => true
    case _: VirtualMachine.MigrationPostCopyEvent => true
    case _ => false
  }

  /** 任务执行前执行的内容。
    *
    * @param context 执行上下文
    */
  override def before(context: CloudEval): Unit = {}

  /** 任务执行后执行的内容。
    *
    * @param context 执行上下文
    */
  override def after(context: CloudEval): Unit = {
    val clock = context.getCurrentClock
    val task = context.getCurrentTask
    task match {
      case t: VirtualMachine.MigrationPostCopyEvent =>
        val cloudlet = t.vm.getCloudlet
        start(cloudlet.cloudletNo) = clock
      case t: PhysicalMachine.VMMigrateInEvent =>
        val cloudlet = t.vm.getCloudlet
        stats.getOrElseUpdate(cloudlet.cloudletNo, new mutable.ListBuffer[Long]) += clock - start(cloudlet.cloudletNo)
        start -= cloudlet.cloudletNo
    }
  }
}
